package com.woniu.timer;

import com.woniu.outlet.elasticSearch.po.Gold;
import com.woniu.outlet.mysql.GoldMysqlMapper;
import com.woniu.outlet.mysql.po.GoldMysql;
import com.woniu.util.DateUtil;
import com.woniu.util.GoldUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: my
 * @time: 2021/4/23 15:25
 */
@Component
@Slf4j
public class GoldTimer {
    private GoldUtils goldUtils;
    private GoldMysqlMapper goldMapper;
    private DateUtil dateUtil;

    private final String DATE_PARRTERN = "yyyy-MM-dd";

    public GoldTimer(GoldUtils goldUtils,GoldMysqlMapper goldMapper,DateUtil dateUtil){
        this.goldUtils = goldUtils;
        this.goldMapper = goldMapper;
        this.dateUtil = dateUtil;
    }

    @Scheduled(cron = "0 0 23 * * ?")
    public void flushGolds(){
        try {
            List<Gold> golds = goldUtils.queryGoldsFromNet();
            if (golds.size() < 1){
                return;
            }
            String now = dateUtil.getDateString(new Date());
            for (Gold gold : golds) {
                String update = dateUtil.getDateString(gold.getUpdatetime());
                if (now.equals(update)){
                    GoldMysql goldMysql = goldUtils.goldToGoldMysql(gold);
                    goldMapper.insert(goldMysql);
                }
            }
            goldUtils.saveGolds(golds);
            log.debug("今日Gold数据刷新完成");
        } catch (Exception e) {
            log.debug("今日黄金数据刷新失败");
        }

    }
}
